package XZK010303.utils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import XZK010303.bean.Express;

/**
 * <p>
 * description
 * </p>
 *
 * @author bing.z 2021/6/21 10:14
 **/
public class IOUtils {
    private static final String filePath = "D://store.txt";
    private static InputStream fileInputStream;
    private static OutputStream fileOutputStream;

    /**
     * 序列化数据至磁盘
     *
     * @param list
     * @throws IOException
     */
    public static void storeObj(List<Express> list) throws IOException {
        fileOutputStream = new FileOutputStream(filePath);
        try (ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);) {
            for (Express express : list) {
                oos.writeObject(express);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 反序列化数据回内存
     *
     * @return
     * @throws IOException
     */
    public static Map<String, Express> restoreObj() throws IOException {
        fileInputStream = new FileInputStream(filePath);
        Map<String, Express> expressesList = new HashMap<>();
        try (ObjectInputStream ois = new ObjectInputStream(fileInputStream);) {
            while (true) {
                Object object = ois.readObject();
                if (object instanceof Express) {
                    Express express = (Express) object;
                    expressesList.put(express.getNumber(), express);
                }
                if (object == null) {
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return expressesList;
    }
}
